package hsb.ruoyi.framework.web.service;

import hsb.ruoyi.common.constant.Constants;
import hsb.ruoyi.common.core.cache.LocalCache;
import hsb.ruoyi.common.core.domain.TokenService;
import hsb.ruoyi.common.core.domain.entity.SysUser;
import hsb.ruoyi.common.core.domain.model.LoginUser;
import hsb.ruoyi.common.exception.ServiceException;
import hsb.ruoyi.common.utils.DateUtils;
import hsb.ruoyi.common.utils.MessageUtils;
import hsb.ruoyi.common.utils.SecurityUtils;
import hsb.ruoyi.framework.manager.AsyncManager;
import hsb.ruoyi.framework.manager.factory.AsyncFactory;
import hsb.ruoyi.system.service.ISysConfigService;
import hsb.ruoyi.system.service.ISysUserService;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@ApplicationScoped
public class SysLoginService {
    @Inject
    TokenService tokenService;

    //  @Inject
    // private AuthenticationManager authenticationManager;

    @Inject
    LocalCache redisCache;

    @Inject
    ISysUserService userService;

    @Inject
    ISysConfigService configService;

    @Inject
    UserDetailsServiceImpl userDetailsService;

    /**
     * 登录验证
     *
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid) {
        boolean captchaOnOff = configService.selectCaptchaOnOff();
        // 验证码开关

        //todo 登陆还没有验证密码
        // 用户验证
        LoginUser loginUser = userDetailsService.loadUserByUsername(username);
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            if (!SecurityUtils.matchesPassword(password, loginUser.getPassword())) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new ServiceException("密码不匹配");
            }
        } catch (Exception e) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, "密码不匹配"));
            throw new ServiceException(e.getMessage());
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, "登录成功"));
        //   LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }


    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        //sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
